package xml;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.util.Log;

public class Writer extends NodeUtilities implements IWriter {

	@Override
	public void writeNodeToXML(String filename, String nodeAttribute,
			String nodeValue) {
		try {
			DocumentBuilderFactory docFactory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
			Document document;
			Element rootElement;

			if (!new File(filename).exists()) {
				new File(filename).createNewFile();
				document = docBuilder.newDocument();
				rootElement = document.createElement("Playlist");
				document.appendChild(rootElement);
			} else {
				document = docBuilder.parse(new File(filename));
				rootElement = document.getDocumentElement();
			}
			
			if (filename.compareTo(defaultPlaylist) == 0) {
				super.setNodeName(nodeNamePlaylist);
			} else {
				super.setNodeName(nodeNameImage);
			}

			if (!existsNode(rootElement, nodeValue)) {

				Element element = document.createElement(super.getNodeName());
				element.setAttribute(attributeName, nodeAttribute);
				element.setTextContent(nodeValue);
				rootElement.appendChild(element);

				super.saveDocument(filename, document);

			}

		} catch (Exception e) {
			Log.e("error", e.getMessage());
		}
	}

	private boolean existsNode(Element rootElement, String name) {

		NodeList list = rootElement.getElementsByTagName(super.getNodeName());

		boolean check = false;

		for (int i = 0; i < list.getLength(); i++) {
			if (list.item(i).getFirstChild().getNodeValue().compareTo(name) == 0) {
				check = true;
			}
		}

		return check;
	}

	/**
	 * 
	 * Elimina il file specificato da filename
	 * 
	 * @param filename
	 */
	public void deletePlaylist(String filename) {
		File file = new File(filename);
		file.delete();
	}
}
